package com.radio.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.radio.R;
import com.radio.RadioApplication;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.IBinder;
import android.util.Log;

/**
 * 
 * @author Max
 *
 */
public class PlayerService extends Service{
	private MediaPlayer mediaPlayer;
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		
		mediaPlayer = new MediaPlayer();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		
		startPlay();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		
		stopPlay();
	}
//---------------------------------------------------------------------------	
	/**
	 * Starts to play music
	 */
	private void startPlay(){
		InputStream instream = getResources().openRawResource(R.raw.ultra_64);
		((RadioApplication)getApplication()).setInstream(instream);
		
		String song = readURLs(instream);

		try {					
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setDataSource(song);
			mediaPlayer.setOnPreparedListener(new OnPreparedListener() {					
				@Override
				public void onPrepared(MediaPlayer arg0) {
					mediaPlayer.start();
				}
			});
			mediaPlayer.prepareAsync();
		} catch (IOException e) {
			Log.e("Error", "No Stream");
		}
	}
//---------------------------------------------------------------------------------
	/**
	 * Stops to play music
	 */
	private void stopPlay(){
		mediaPlayer.stop();
		mediaPlayer.release();
	}
//----------------------------------------------------------------------------------	
	/**
	 * 
	 * @param instream audio stream
	 * @return URL string
	 */
	public String readURLs(InputStream instream) {
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(instream));
			String song = in.readLine();
			in.close();
			return song;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
